package cn.jingyuan.bee.fastjson;

import cn.jingyuan.bee.enums.EnumString;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.util.TypeUtils;

import java.io.IOException;
import java.lang.reflect.Type;


public class EnumStringSerializer implements ObjectSerializer, ObjectDeserializer {

    public static final EnumStringSerializer instance = new EnumStringSerializer();

    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        Object value = parser.parse();
        Class clazz = (Class) type;
        if (null == value) {
            return null;
        }
        return (T) EnumString.from(clazz, TypeUtils.castToString(value));
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_INT;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        serializer.write(((EnumString) object).getValue());
    }

}
